package cn.com.xxlibrary.dao.impl;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import cn.com.xxlibrary.dao.IBookDao;
import cn.com.xxlibrary.orm.BooksBean;
import cn.com.xxlibrary.util.UtilTools;

@Transactional
@Repository("bookDao")
public class BookDaoImpl implements IBookDao {

	@Autowired
	@Qualifier("sessionFactory")
	private SessionFactory sessionFactory;
	
	public BooksBean queryBook(int id){
		Session session = sessionFactory.getCurrentSession();
		return (BooksBean) session.get(BooksBean.class, id);
	}
	
	public void addBook(BooksBean book){
		Session session = sessionFactory.getCurrentSession();
		session.saveOrUpdate(book);
	}
	
	public void delBook(int id){
		Session session = sessionFactory.getCurrentSession();
		BooksBean book = (BooksBean) session.get(BooksBean.class, id);
		if (UtilTools.isNotNullorEmpty(book)){
			session.delete(book);
		}
	}
	
	public Map listBook(int start, int pageSize){
		Session session = sessionFactory.getCurrentSession();
		String HQL = "FROM BooksBean ORDER BY bookStorageTime DESC";
		Query query = session.createQuery(HQL);

		int c = query.list().size();
		query.setFirstResult(start);
		query.setMaxResults(pageSize);

		List<?> list = query.list();

		Map<String, Object> map = new LinkedHashMap<String, Object>();
		map.put("count", c);
		map.put("queryResult", list);

		return map;
	}
}
